<template>
	<view class="container">
		<!-- 店铺信息 -->
		<view class="shop-section" :class="[!shopExpanded ? 'collapsed' : '']">
			<view class="shop-info" @click="toggleShopInfo">
				<image class="shop-avatar" src="/static/images/user.png" mode="aspectFill"></image>
				<view class="shop-details">
					<text class="shop-name">{{  storeInfo.name  }}</text>
					<view class="shop-notices">
						<text class="shop-notice">{{ storeInfo.address }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 收货地址 -->
		<view v-if="deliveryMethod === 'express'" class="address-section" @click="selectAddress">
			<view class="address-content">
				<image class="address-icon" src="/static/image/icon_location_order.png" mode="aspectFit"></image>
				<view class="address-info">
					<text class="address-text">{{address.address || '请选择收货地址'}}</text>
					<text class="address-user">{{address.nickname}} {{address.phone}}</text>
				</view>
				<image class="arrow-icon" src="/static/icon/right.png" mode="aspectFit"></image>
			</view>
		</view>

		<!-- 收货方式 -->
		<view class="delivery-section">
			<text class="section-title">收货方式</text>
			<view class="delivery-options">
				<view class="delivery-option" :class="[deliveryMethod === 'express' ? 'selected' : '']" @click="selectDeliveryMethod('express')">
					<view class="radio-btn" :class="[deliveryMethod === 'express' ? 'checked' : '']">
						<text v-if="deliveryMethod === 'express'" class="check-icon">✓</text>
					</view>
					<text class="option-text">包邮</text>
				</view>
				<view class="delivery-option" :class="[deliveryMethod === 'self_pickup' ? 'selected' : '']" @click="selectDeliveryMethod('self_pickup')">
					<view class="radio-btn" :class="[deliveryMethod === 'self_pickup' ? 'checked' : '']">
						<text v-if="deliveryMethod === 'self_pickup'" class="check-icon">✓</text>
					</view>
					<text class="option-text">自提</text>
				</view>
			</view>
		</view>

		<!-- 加工详情 -->
		<view class="process-section">
			<view class="process-item">
				<text class="process-label">参数类型</text>
				<text class="process-value">{{ orderParams && orderParams.param_type === 'workshop' ? '工坊参数' : '上传参数' }}</text>
			</view>
			<view class="process-item">
				<text class="process-label">加工类型</text>
				<text class="process-value">{{ processType || '未选择' }}</text>
			</view>
			<view class="process-item">
				<text class="process-label">机器</text>
				<text class="process-value">{{ orderParams.device || '未选择' }}</text>
			</view>
			<view class="process-item">
				<text class="process-label">材料</text>
				<text class="process-value">{{ getMaterialInfo() }}</text>
			</view>
			<view v-if="showCraftParams" class="process-item">
				<text class="process-label">工艺参数</text>
				<text class="process-value">{{ formatCraftParams(craftParams) }}</text>
			</view>
		</view>
		<!-- 模型上传 -->
		<view class="upload-section">
			<!-- 如果是上传参数模式且有模型说明，显示说明 -->
			<view v-if="showModelDescription" class="model-description">
				<text class="section-title">模型说明</text>
				<text class="description-text">{{ uploadModelDescription }}</text>
			</view>

			<view v-if="!modelFile" class="upload-area" @click="uploadModel">
				<image class="upload-icon" src="/static/image/icon_upload_model.png" mode="aspectFit"></image>
				<text class="upload-text">上传模型文件(支持.STL/.STRP格式)</text>
			</view>
			<view v-else class="uploaded-file">
				<view class="file-info">
					<image class="file-icon" src="/static/icon/success.png" mode="aspectFit"></image>
					<text class="file-name">{{modelFile.name || '模型文件'}}</text>
				</view>
				<view class="file-actions">
					<text class="reupload-btn" @click="uploadModel">重新上传</text>
				</view>
			</view>
		</view>

		<!-- 备注 -->
		<view class="remark-section">
			<text class="section-title">备注</text>
			<textarea
				v-model="remark"
				placeholder="请添加备注信息"
				class="remark-input"
				maxlength="200"
			></textarea>
		</view>

		<!-- 底部操作栏 -->
		<view class="bottom-bar">
			<view class="service-btn" @click="contactService">
				<image class="service-icon" src="/static/image/icon_service.png" mode="aspectFit"></image>
				<text class="service-text">客服</text>
			</view>
			<view class="submit-btn" :class="[loading ? 'disabled' : '']" @click="submitOrder">
				<text class="submit-text">{{loading ? '提交中...' : '提交'}}</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				storeInfo: {},
				address: {},
				deliveryMethod: 'express', // express: 包邮, self_pickup: 自提
				processFileName: 'UTM-K',
				modelFile: null,
				remark: '',
				loading: false,
				shopExpanded: true, // 店铺信息展开状态

				// 订单参数相关
				orderParams: null, // 完整的订单参数对象
				processType: '', // 加工类型
				material: '', // 材料
				craftParams: [], // 工艺参数
				uploadModelDescription: '', // 上传的模型说明
				materialData: null, // 材料数据
				selectedColorIndex: -1, // 选择的颜色索引
			}
		},
		computed: {
			// 获取材料颜色名称
			materialColorName() {
				if (this.materialData && this.selectedColorIndex >= 0 && this.materialData.colors && this.materialData.colors[this.selectedColorIndex]) {
					return this.materialData.colors[this.selectedColorIndex].name;
				}
				return '';
			},

			// 是否显示模型说明
			showModelDescription() {
				return this.orderParams && this.orderParams.param_type === 'upload' && this.uploadModelDescription;
			},

			// 是否显示工艺参数
			showCraftParams() {
				return this.craftParams && this.craftParams.length > 0;
			},
		},
		onLoad(options) {
			// 检查用户是否已登录
			if (!this.userInfo.id) {
				uni.showModal({
					title: '提示',
					content: '请先登录后再申请下单',
					success: (res) => {
						if (res.confirm) {
							uni.navigateTo({
								url: '/pages/login/index'
							});
						} else {
							uni.navigateBack();
						}
					}
				});
				return;
			}

			// 处理传递的参数数据
			if (options.params) {
				try {
					const paramsData = JSON.parse(decodeURIComponent(options.params));
					console.log('paramsData', paramsData);
					this.orderParams = paramsData;

					// 根据参数类型设置不同的显示内容
					// 工坊参数模式
					this.processType = paramsData.process_type || '';
					this.material = paramsData.material || '';
					this.craftParams = paramsData.craft_params || [];

					// 如果有材料数据，显示材料颜色信息
					if (paramsData.material_data) {
						this.materialData = paramsData.material_data;
					}

					// 如果有选择的颜色索引
					if (paramsData.selected_color_index !== undefined) {
						this.selectedColorIndex = paramsData.selected_color_index;
					}
					// 上传参数模式
					this.uploadModelDescription = paramsData.upload_params?.model_description || '';
					if (paramsData.upload_params?.model_file) {
						this.modelFile = paramsData.upload_params.model_file;
					}
				} catch (error) {
					console.error('解析参数数据失败:', error);
					uni.showToast({
						title: '参数数据解析失败',
						icon: 'none'
					});
				}
			}

			this.getStoreDetail(options.id)
			// 如果默认是快递模式，获取默认地址
			if (this.deliveryMethod === 'express') {
				this.getDefaultAddress();
			}
		},
		onShow() {
			// 检查是否有新选择的地址
			const selectedAddress = uni.getStorageSync('selectedAddress');
			if (selectedAddress) {
				this.address = selectedAddress;
				uni.removeStorageSync('selectedAddress')
			}
		},
		methods: {
			// 切换店铺信息展开状态
			toggleShopInfo() {
				this.shopExpanded = !this.shopExpanded;
			},

			// 获取默认地址
			getDefaultAddress() {
				if (!this.userInfo.id) return;

				this.$api.getAddressList({
					user_id: this.userInfo.id
				}).then(res => {
					if (res && res.length > 0) {
						// 找到默认地址或使用第一个地址
						const defaultAddress = res.find(item => item.status === 1) || res[0];
						this.address = defaultAddress;
					}
				}).catch(error => {
					console.error('获取地址失败:', error);
				});
			},
			getStoreDetail(id) {
				this.$api.getWorkShopDetail(id).then(res => {
					this.storeInfo = res;
				});
			},
			// 选择地址
			selectAddress() {
				uni.navigateTo({
					url: '/pages/address/address'
				});
			},

			// 选择收货方式
			selectDeliveryMethod(method) {
				this.deliveryMethod = method;

				// 如果切换到快递模式且没有地址，自动获取默认地址
				if (method === 'express' && !this.address.id) {
					this.getDefaultAddress();
				}
			},

			// 选择工艺参数文件
			selectProcessFile() {
				uni.showActionSheet({
					itemList: ['UTM-K', 'UTM-L', 'UTM-M'],
					success: (res) => {
						const files = ['UTM-K', 'UTM-L', 'UTM-M'];
						this.processFileName = files[res.tapIndex];
					}
				});
			},

			// 上传模型文件
			uploadModel() {
				// 使用uni.chooseFile选择文件（小程序端）
				// #ifdef MP-WEIXIN
				uni.chooseMessageFile({
					count: 1,
					type: 'file',
					success: (res) => {
						const file = res.tempFiles[0];

						// 检查文件扩展名
						const fileName = file.name || '';
						const validExtensions = ['.stl', '.strp'];
						const isValidFile = validExtensions.some(ext =>
							fileName.toLowerCase().endsWith(ext)
						);

						if (!isValidFile) {
							uni.showToast({
								title: '请选择.STL或.STRP格式文件',
								icon: 'none'
							});
							return;
						}

						// 检查文件大小（限制50MB）
						if (file.size > 50 * 1024 * 1024) {
							uni.showToast({
								title: '文件大小不能超过50MB',
								icon: 'none'
							});
							return;
						}

						// 上传文件
						this.uploadModelFile(file.path);
					},
					fail: (err) => {
						console.error('选择文件失败:', err);
					}
				});
				// #endif

				// #ifdef H5
				// H5端使用input file
				const input = document.createElement('input');
				input.type = 'file';
				input.accept = '.stl,.strp';
				input.onchange = (e) => {
					const file = e.target.files[0];
					if (file) {
						// 检查文件大小（限制50MB）
						if (file.size > 50 * 1024 * 1024) {
							uni.showToast({
								title: '文件大小不能超过50MB',
								icon: 'none'
							});
							return;
						}

						// 上传文件
						this.uploadModelFile(file);
					}
				};
				input.click();
				// #endif
			},

			// 上传模型文件到服务器
			uploadModelFile(file) {
				uni.showLoading({
					title: '上传中...'
				});

				// #ifdef MP-WEIXIN
				// 小程序端使用uni.uploadFile
				uni.uploadFile({
					url: this.$api.uploadImage,
					filePath: file,
					name: 'file',
					success: (res) => {
						this.handleUploadSuccess(res);
					},
					fail: (error) => {
						this.handleUploadFail(error);
					},
					complete: () => {
						uni.hideLoading();
					}
				});
				// #endif

				// #ifdef H5
				// H5端使用FormData上传
				const formData = new FormData();
				formData.append('file', file);

				uni.request({
					url: this.$api.uploadImage,
					method: 'POST',
					data: formData,
					header: {
						'Token': uni.getStorageSync('Token'),
						'X-Requested-With': 'XMLHttpRequest',
					},
					success: (res) => {
						this.handleUploadSuccess(res);
					},
					fail: (error) => {
						this.handleUploadFail(error);
					},
					complete: () => {
						uni.hideLoading();
					}
				});
				// #endif
			},

			// 处理上传成功
			handleUploadSuccess(res) {
				try {
					let data;
					// #ifdef MP-WEIXIN
					data = JSON.parse(res.data);
					// #endif

					// #ifdef H5
					data = res.data;
					// #endif

					if (data.code === 200) {
						this.modelFile = data.data;
						uni.showToast({
							title: '上传成功',
							icon: 'success'
						});
					} else {
						uni.showToast({
							title: data.message || '上传失败',
							icon: 'none'
						});
					}
				} catch (error) {
					uni.showToast({
						title: '上传失败',
						icon: 'none'
					});
				}
			},

			// 处理上传失败
			handleUploadFail(error) {
				console.error('上传失败:', error);
				uni.showToast({
					title: '上传失败',
					icon: 'none'
				});
			},

			// 格式化工艺参数显示
			formatCraftParams(params) {
				if (!params || !Array.isArray(params)) {
					return '';
				}
				return params.join('、');
			},

			// 获取材料完整信息
			getMaterialInfo() {
				let info = this.material || '未选择';
				if (this.materialColorName) {
					info += ` (${this.materialColorName})`;
				}
				return info;
			},

			contactService() {
				this.$goPage({
					url: `/pages/service/chat?id=${this.storeInfo.id}&name=${this.storeInfo.name}`,
					needLogin: true
				})
			},

			// 提交订单
			submitOrder() {
				// 防止重复提交
				if (this.loading) {
					return;
				}

				// 检查用户是否已登录
				if (!this.userInfo.id) {
					uni.showModal({
						title: '提示',
						content: '请先登录',
						success: (res) => {
							if (res.confirm) {
								uni.navigateTo({
									url: '/pages/login/index'
								});
							}
						}
					});
					return;
				}

				// 验证必填项
				if (this.deliveryMethod === 'express' && !this.address.id) {
					uni.showToast({
						title: '请选择收货地址',
						icon: 'none'
					});
					return;
				}

				// 根据参数类型验证模型文件
				// if (this.orderParams && this.orderParams.param_type === 'upload') {
				// 	// 上传参数模式必须上传模型文件
				// 	if (!this.modelFile) {
				// 		uni.showToast({
				// 			title: '请上传模型文件',
				// 			icon: 'none'
				// 		});
				// 		return;
				// 	}
				// } else {
				// 	// 工坊参数模式，模型文件可选
				// 	if (!this.modelFile) {
				// 		uni.showToast({
				// 			title: '请上传模型文件',
				// 			icon: 'none'
				// 		});
				// 		return;
				// 	}
				// }

				// 构建订单数据
				const orderData = {
					user_id: this.userInfo.id,
					store_id: this.orderParams?.store_id,
					order_delivery: this.deliveryMethod,
					model_file:this.modelFile && this.modelFile.url,
					remark: this.remark,
					// 包含完整的参数数据
					order_params: JSON.stringify(this.orderParams),
					// 这里可以添加其他订单相关数据，如商品信息、价格等
				};

				// 根据收货方式添加地址信息
				if (this.deliveryMethod === 'express') {
					orderData.address_id = this.address.id;
					orderData.address_detail = this.address.address + ' ' + this.address.house;
					orderData.address_nickname = this.address.nickname;
					orderData.address_phone = this.address.phone;
				}

				this.loading = true;
				uni.showLoading({
					title: '提交中...'
				});

				// 提交订单
				this.$api.createOrder(orderData).then(res => {
					uni.hideLoading();
					this.loading = false;
					uni.showToast({
						title: '订单提交成功',
						icon: 'success'
					});

					// 跳转到订单详情页
					setTimeout(() => {
						uni.redirectTo({
							url: `/pages/order/detail?id=${res.id}`
						});
					}, 1500);
				}).catch(error => {
					uni.hideLoading();
					this.loading = false;
					console.error('提交订单失败:', error);
					uni.showToast({
						title: '提交失败，请重试',
						icon: 'none'
					});
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
.container {
	min-height: 100vh;
	background-color: #f5f5f5;
	padding-bottom: 120rpx;
}

.shop-section {
	background: #fff;
	padding: 30rpx;
	margin-bottom: 20rpx;
	display: flex;
	align-items: flex-start;
	justify-content: space-between;

	&.collapsed {
		padding: 20rpx 30rpx;
	}

	.shop-info {
		display: flex;
		align-items: flex-start;
		flex: 1;
		cursor: pointer;
		&:active {
			opacity: 0.7;
		}

		.shop-avatar {
			width: 80rpx;
			height: 80rpx;
			border-radius: 50%;
			margin-right: 20rpx;
		}

		.shop-details {
			flex: 1;

			.shop-name {
				font-size: 32rpx;
				font-weight: 600;
				color: #333;
				display: block;
				margin-bottom: 10rpx;
			}

			.shop-notices {
				overflow: hidden;

				.shop-notice {
					font-size: 26rpx;
					color: #999;
					display: block;
					line-height: 1.4;
					margin-bottom: 6rpx;

					&:last-child {
						margin-bottom: 0;
					}
				}
			}

			.shop-brief {
				font-size: 24rpx;
				color: #999;
				font-style: italic;
			}
		}
	}

	.collapse-btn {
		font-size: 28rpx;
		color: #539DF3;
		padding: 10rpx 20rpx;
		border-radius: 6rpx;
	}
}

.address-tip {
	background: #fff7e6;
	border: 1rpx solid #ffd591;
	border-radius: 8rpx;
	margin: 0 30rpx 20rpx;
	padding: 20rpx 30rpx;

	.tip-text {
		font-size: 26rpx;
		color: #d46b08;
		text-align: center;
		display: block;
	}
}

.address-section {
	background: #fff;
	margin: 0 30rpx 20rpx;
	border-radius: 16rpx;
	padding: 30rpx;

	.address-content {
		display: flex;
		align-items: center;

		.address-icon {
			width: 48rpx;
			height: 48rpx;
			margin-right: 20rpx;
		}

		.address-info {
			flex: 1;

			.address-text {
				font-size: 30rpx;
				color: #333;
				font-weight: 600;
				display: block;
				margin-bottom: 8rpx;
			}

			.address-user {
				font-size: 26rpx;
				color: #999;
			}
		}

		.arrow-icon {
			width: 64rpx;
			height: 64rpx;
		}
	}
}

.delivery-section {
	background: #fff;
	margin: 0 30rpx 20rpx;
	border-radius: 16rpx;
	padding: 30rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;

	.section-title {
		font-size: 30rpx;
		color: #333;
		font-weight: 600;
		display: block;
	}

	.delivery-options {
		display: flex;
		gap: 40rpx;

		.delivery-option {
			display: flex;
			align-items: center;

			.radio-btn {
				width: 40rpx;
				height: 40rpx;
				border: 2rpx solid #ddd;
				border-radius: 50%;
				margin-right: 16rpx;
				display: flex;
				align-items: center;
				justify-content: center;

				&.checked {
					border-color: #539DF3;
					background: #539DF3;

					.check-icon {
						color: #fff;
						font-size: 24rpx;
						font-weight: bold;
					}
				}
			}

			.option-text {
				font-size: 28rpx;
				color: #333;
			}
		}
	}
}

.process-section {
	background: #fff;
	margin: 0 30rpx 20rpx;
	border-radius: 16rpx;
	padding: 30rpx;

	.process-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;

		&:last-child {
			margin-bottom: 0;
		}

		.process-label {
			font-size: 28rpx;
			color: #666;
		}

		.process-value {
			font-size: 28rpx;
			color: #333;
			font-weight: 600;

			.color-info {
				font-size: 24rpx;
				color: #539DF3;
				font-weight: normal;
				margin-left: 10rpx;
			}
		}
	}
}

.file-section {
	background: #fff;
	margin: 0 30rpx 20rpx;
	border-radius: 16rpx;
	padding: 30rpx;

	.section-title {
		font-size: 30rpx;
		color: #333;
		font-weight: 600;
		// margin-bottom: 20rpx;
		display: block;
	}

	.file-content {
		display: flex;
		align-items: center;
		justify-content: space-between;

		.file-name {
			font-size: 28rpx;
			color: #333;
		}

		.arrow-icon {
			width: 32rpx;
			height: 32rpx;
		}
	}
}

.upload-section {
	margin: 0 30rpx 20rpx;

	.model-description {
		background: #fff;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;

		.section-title {
			display: block;
			font-size: 28rpx;
			color: #333;
			font-weight: 500;
			margin-bottom: 16rpx;
		}

		.description-text {
			font-size: 26rpx;
			color: #666;
			line-height: 1.6;
		}
	}

	.upload-area {
		background: #fff;
		border: 2rpx dashed #ddd;
		border-radius: 16rpx;
		padding: 80rpx 40rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;

		.upload-icon {
			width: 160rpx;
			height: 160rpx;
			margin-bottom: 40rpx;
		}

		.upload-text {
			font-size: 28rpx;
			color: #666;
			text-align: center;
		}
	}

	.uploaded-file {
		background: #fff;
		border-radius: 16rpx;
		padding: 30rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;

		.file-info {
			display: flex;
			align-items: center;
			flex: 1;

			.file-icon {
				width: 40rpx;
				height: 40rpx;
				margin-right: 20rpx;
			}

			.file-name {
				font-size: 28rpx;
				color: #333;
				font-weight: 600;
			}
		}

		.file-actions {
			.reupload-btn {
				font-size: 26rpx;
				color: #539DF3;
				padding: 10rpx 20rpx;
				border: 1rpx solid #539DF3;
				border-radius: 6rpx;

				&:active {
					background: #539DF3;
					color: #fff;
				}
			}
		}
	}
}

.remark-section {
	background: #fff;
	margin: 0 30rpx 20rpx;
	border-radius: 16rpx;
	padding: 30rpx;

	.section-title {
		font-size: 30rpx;
		color: #333;
		font-weight: 600;
		margin-bottom: 20rpx;
		display: block;
	}

	.remark-input {
		width: 100%;
		min-height: 120rpx;
		border: 1rpx solid #eee;
		border-radius: 8rpx;
		padding: 20rpx;
		font-size: 28rpx;
		color: #333;
		box-sizing: border-box;
	}
}

.bottom-bar {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background: #fff;
	padding: 20rpx 30rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	border-top: 1rpx solid #eee;

	.service-btn {
		display: flex;
		align-items: center;

		.service-icon {
			width: 40rpx;
			height: 40rpx;
			margin-right: 10rpx;
		}

		.service-text {
			font-size: 28rpx;
			color: #333;
		}
	}

	.submit-btn {
		flex-grow: 1;
		text-align: center;
		background: #333;
		border-radius: 8rpx;
		padding: 20rpx 60rpx;
		margin-left: 60rpx;

		&.disabled {
			background: #ccc;
			pointer-events: none;
		}

		.submit-text {
			color: #fff;
			font-size: 30rpx;
			font-weight: 600;
		}
	}
}
</style>
